package com.sh.data.engine.repository.dao.normalization.standard;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.sh.data.engine.repository.dao.normalization.standard.entity.DictionaryMappingEntity;
import org.springframework.stereotype.Repository;

import java.util.Objects;

/**
 * @author jingchen.hr
 */
@Repository
public interface DictionaryMappingMapper extends BaseMapper<DictionaryMappingEntity> {

    /**
     * 绑定数量更新
     *
     * @param id
     * @param boundCount
     * @param notBoundCount
     */
    default int updateBoundCountById(Long id, Integer boundCount, Integer notBoundCount) {
        DictionaryMappingEntity original = this.selectById(id);
        if (Objects.equals(original.getRowState(), 0)) {
            return 0;
        }
        boundCount += original.getBoundCount();
        notBoundCount += original.getNotBoundCount();

        LambdaUpdateWrapper<DictionaryMappingEntity> update =
            new UpdateWrapper<DictionaryMappingEntity>().lambda();
        update
            .eq(DictionaryMappingEntity::getId, id)
            .set(DictionaryMappingEntity::getBoundCount, boundCount)
            .set(DictionaryMappingEntity::getNotBoundCount, notBoundCount);
        return this.update(null, update);
    }


    default DictionaryMappingEntity getDictMappingByProjectAndDict(Long projectId, Long dictId) {

        LambdaQueryWrapper<DictionaryMappingEntity> query = new QueryWrapper<DictionaryMappingEntity>().lambda();
        query.eq(DictionaryMappingEntity::getRowState, 1)
            .eq(Objects.nonNull(projectId), DictionaryMappingEntity::getProjectId, projectId)
            .eq(Objects.nonNull(dictId), DictionaryMappingEntity::getDictId, dictId)
            .orderByAsc(DictionaryMappingEntity::getId);
        return this.selectOne(query);
    }

    default Long countByProjectIdAndDictId(Long projecId, Long dictId) {

        LambdaQueryWrapper<DictionaryMappingEntity> query = new QueryWrapper<DictionaryMappingEntity>().lambda();
        query.eq(DictionaryMappingEntity::getProjectId, projecId).eq(DictionaryMappingEntity::getDictId, dictId);
        return this.selectCount(query);
    }


}
